import codeFormat from './htmlFormat'
import bus from '../../../utils/bus'
class eeSourceBtn {
    constructor(quill, options) {
  
      let theClass = this;
  
      theClass.addDom(quill);
      quill.on('text-change', (delta, oldDelta, source)=>{
        theClass.replaceSourceEditorContent(quill)
      })
      
      //create btn
      let button = document.createElement("button");
      //display button text
      button.innerHTML = ">_";
      button.onclick = function() {
        theClass.showSourceEditor(quill);
      };
  
      //create btn container
      let buttonContainer = document.createElement("span");
      buttonContainer.setAttribute("class", "ql-formats ee-flag-source");
      buttonContainer.appendChild(button);
      
      //add to toolbar
      quill.container.previousSibling.appendChild(buttonContainer);
      
    }
  
    //add dom for source editor
    addDom(quill){
      if (!quill.container.querySelector(".ql-ee-source")) {
        var txtArea = document.createElement('textarea');
        txtArea.style.cssText = "width: 50%;margin: auto;background: rgb(29, 29, 29);box-sizing: border-box;color: rgb(204, 204, 204);font-size: 13px;outline: none;padding: 12px 15px;line-height: 1.42;font-family: Consolas, Menlo, Monaco, &quot;Courier New&quot;, monospace;position: absolute;top: 0;bottom: 0;border: none;"

        var htmlEditor = quill.addContainer('ql-ee-source')
        htmlEditor.style.cssText = "display:none";
        htmlEditor.appendChild(txtArea)
      }
    }
  
    //for quill editor switch
    replaceSourceEditorContent(quill){
      let quillEditor = quill.container.querySelector(".ql-editor");
      let sourceContainer = quill.container.querySelector(".ql-ee-source");
      let sourceEditor = sourceContainer.querySelector('textarea');
  
      sourceEditor.value = quillEditor.innerHTML;
  
    }
  
    //add html DOM, show/hide, save event
    showSourceEditor(quill) {
      //1. find quill editor
      let quillEditor = quill.container.querySelector(".ql-editor");
  
      let sourceContainer = quill.container.querySelector(".ql-ee-source");
      let sourceEditor = sourceContainer.querySelector('textarea');

      quillEditor.style.display = 'none'
      // console.log(sourceEditor);
  
  
      //show/hide editor, value transfer
      if (sourceContainer.style.display === 'none') {
        //show source editor
        sourceContainer.style.display = '';
        quillEditor.style.cssText = "width:50%";
  
        sourceEditor.value = codeFormat.format(quillEditor.innerHTML);
      }else{
        //hidden source ditor
        sourceContainer.style.display = 'none';

        quillEditor.style.cssText = "width:100%";
        //set source content to quill editor
        quillEditor.innerHTML = sourceEditor.value;
      }
  
    }
    
  
  }
  
  window.eeSourceBtn = eeSourceBtn;
  export default eeSourceBtn;
  export { eeSourceBtn };
  